# -*- coding: utf-8 -*-
import ahocorasick
import re
import json
from lxml import etree
import time
import datetime
import requests
from bs4 import BeautifulSoup
import html_text

class Ac_match():
    def __init__(self):
        self.reg1 = re.compile("<.*?>")
        self.cgr_keyword = ["采购人信息", "采购单位信息", "采购人", "招标人", "采购单位"]
        self.dl_keyword = ["采购代理机构信息", "采购代理机构", "招标组织机构", "代理机构"]
        self.fb_rule = ['因#不足三家_50', '因#不足法定_50', '供应商不足三家', '本#废标_30', '废标原因', '中标结果无效', '投标供应商不足#流标_50', '因#不明确致采购失败_50', '供应商不足#废标_50', '报价人不足#失败_150', '投标人少于#流标_50', '本项目采购终止', '因#终止招标_50', '供应商不足#失败_50', '供应商不足法定数量', '不足法定#失败_50', '响应家数不足#失败_50', '采购工作终止', '投标单位不足#废标_50', '本项目予以废标处理', '采购活动取消', '参选人不足#失败_100', '终止本项目本次采购', '有效磋商供应商均不足#废标_50', '因无符合资格的竞价人而未能成功交易', '未抽取足够专家#采购失败_50', '只有#家供应商参加，则询价失败_10', '报名单位不足#询价失败_50', '投标的单位不足#废标_50', '没有投标单位报名#废标_50', '无有效投标人#失败_50', '供应商#谈判失败_50', '本项目废标', '本次评标作废标处理', '供应商不足#流标', '本项目谈判失败', '只有#家投标单位参与投标_30', '单位不足#失败_100', '本项目本次磋商失败', '报名家数不足#失败_30', '本项目询价失败', '无报价人递交报价文件#询价失败_30', '没有投标人报名#失败_50', '本项目招标失败', '终止本项目的招标工作', '投标单位不足#失败_50', '响应人不足#家#失败_50', '投标报名家数不足#失败_50', '中止采购活动', '终止#采购活动_30', '根据#原中标资格无效_50', '投标人不足#失败_50', '投标人不足#废标_50', '本项目作废标处理', '由于不满足#失败_50', '采购任务取消', '投标人家数不足#失败_50', '供应商少于#失败_50', '因#取消本次采购活动_50', '本项目比选失败', '无中标（成交）供应商', '本项目采购失败', '投标人少于#失败_30', '取消#采购项目_30', '无有效的参选人#失败_50', '本次招标项目流标', '本次公开询价失败', '取消相关招标工作', '本项目终止', '竞价失败', '此项目作以废标处理', "废标公告", "中止采购公告", "采购失败公示", "招标失败", "失败公告", "本#不足_50", "因#项目终止_50", "供应商数量不足#失败_50", "无中标供应商", "本项目予以废标", "供应商不足法定三家#废标_50", "投标人不足#家_10", "招标人不足#家_10", "报价人不足#家_10", "中标结果#无效_20", "废标#原因_30", "项目#招标失败_50", "项目#废标_30", "本#不足法定三家_30", "报名单位不足三家", "因#不足法定家数_30", "项目#废标_30", "因本项目#不足三家_50", "因作出#不足法定数量_50", "本#废标_50", "招标人不足三家#失败_50", "招标人不足三家#废标_50", "投标人不足三家#废标_50", "投标人不足三家#失败_50", "供应商不足三家#废标_50", "供应商不足三家#失败_50"]
        self.unknow_dict = {'项目编号': ['采购项目编号：', '标段（包）编号：', '标段编号：', '项目编号:',
                                       '项目编号', '招标编号：', '招标编号:', '招标编号', '采购编号：',
                                       '采购编号:', '采购编号', '机构编号：', '采购计划编号：', '代理编号：',
                                       '委托编号：', '招标人编号：', '招标人编号:', '采购人编号：',
                                       '项目受理编号：', '招标文件编号：', '招标文件编号:', '采购文件编号',
                                       '招标项目编号：', '竞价编号：', '文件编号：', '工程编号：', '工程编号:',
                                       '工程编号', '项目统一代码：', '项目统一代码:', '公告编号'],
                            "开标变更时间": ["截止时间和开标时间：", "开标时间:"]}
        pass

    # 判断是否为多包
    def bag_judge(self, name):
        if name in ['-1','-2']:
            return 'False'
        pattern = '(包|组|标|段|目)[0-9A-Za-z一二三四五六七八九]+[)）]*$|[（(]*[-]*[0-9A-Za-z一二三四五六七八九]+[期包]*[)）]*$'
        pattern_key = '[0-9A-Za-z一二三四五六七八九]'
        flag = re.search(pattern, name)
        if flag:
            match = flag.group(0)
            if len(match) <= 4:
                flag_key = re.search(pattern_key, match)
                if flag_key:
                    return 'True'
        return 'False'
    
    #获取两个词最邻近的位置
    def get_nearly_word(self, word1, word2, doc):
        word1_list=[i.start() for i in re.finditer(word1, doc)]
        word2_list=[i.start() for i in re.finditer(word2, doc)]
        near_ind = 0
        near_dis = 0
        for p1 in word1_list:
            for p2 in word2_list:
                p_dis = p2-p1
                if p_dis > 0 and near_dis == 0:
                    near_ind = p1
                    near_dis = p_dis
                elif p_dis > 0 and near_dis > p_dis:
                    near_dis = p_dis
                    near_ind = p1
        return near_ind
    

    # 处理html源码
    """
    获取源码内容
    再用正则去除没删干净的<>
    特殊关键词前加空格
    特殊字符替换
    """
    def del_html(self,input_doc, input_dict = {}, notice_status=""):
        rep_list = ['采购项目联系人（采购单位）:', "候选中标供应商：", "批准书文号：", "第二成交候选人", "地 址：", "招标代理服务费：", "地     址：", "评标日期：", "详见：", "详见:", "工期:", "联系地址:", "合同附件：", "投标登记时间：", "工 程 名 称：", "工 程 编 号：", "地  址：", "采购项目简要说明", "商务得分:", "技术得分：", "报价得分：" "联　系　人：", "2.项目编号", "项目编号", "中标供应商开户行  ：", "规格型号：", "合同编号：", "合同金额(元)：", "合同签订日期：", "采购人（全称）：", "询价小组按照询价文件的要求", "评标委员会依据招标文件", "磋商小组依据磋商文件", '经评审小组评审', "谈判小组依据", "项目分包（标段）：", "评委姓名：", "采购项目用途", "采购代理机构内部", "采购代理机构内部编号：", "项目联系人：", "联系人：", "项目序列号:", "项目序列号：", "预算编号：",  "负责人：", "成员：", "成交供应商名称及成交金额：", "成交供应商地址：", "项目总金额：", "入围单位名称和地址、成交金额：", "采购项目名称", "项目负责人：", "中标单位名称及中标金额：", '采购项目联系人（采购单位）：', '项目总报价（含税）（元）：', '项目总报价（含税）（元）:', '中标（成交）金额（元）：', '中标（成交）金额（元）:', '中标（成交）供应商名称:', '中标（成交）供应商名称：', "中标单价合计金额：", '中标、成交金额（万元）', '中标、成交金额(万元)', '最高限价（预算金额）：', '项目规模（预算限额）：', '资金来源（预算限额）：', '项目预算金额（含税）：', '采购预算总额（含税）：', '采购项目预算金额（元）', '中标、成交供应商名称:', '中标、成交供应商名称：', '中标、成交金额（元）', '统一社会信用代码：', '中标、成交金额(元)', "采购需求：",  '项目总报价（含税）：', '项目总报价（含税）:', '项目承包结算价（元）', '中标价格（人民币元）', '中标价格(人民币元)', '采购预算金额（万元）', '第一中标候选供应商:', "中标供应商地址：", '第一中标候选供应商：', '采购代理机构名称：', '中标单价合计金额：', '采购代理机构地址：', '总中标金额（元）：', '总中标金额（元）:', "招标范围：", "中标服务工时：", '总成交金额（元）：', '总成交金额（元）:', '中标（成交）金额：', '中标（成交）金额:', '最终报价为（元）：', '最终报价为（元）:', '最高投标限价如下：', '预算（最高限价）为', '采购项目总预算金额', '第一中标候选供应商', '第一中标候选人名称', '标段（包）编号：', '标段（包）名称：', '中标金额（元）：', '中标金额（元）:', '中标金额（万元）', '中标金额(万元)', '中标总价（元）：', '中标总价（元）:', '中标总价（万元）', '中标总价(万元)', '中标价格（元）：', '中标价格（元）:', '成交金额（元）：', '成交金额（元）:', '成交金额（万元）', '成交金额(万元)', '成交总价（元）：', '成交总价（元）:', '成交价格（元）：', '成交价格（元）:', '预算金额（元）：', '（即最高限价）：', '预算金额(元)：', '采购预算（元）：', '本项目预算金额为', '采购项目预算金额', '招标项目预算金额', '采购代理机构全称', '成交供应商名称:', '成交供应商名称：', '第一中标候选人:', '第一中标候选人：', '第一成交候选人:', '第一成交候选人：', '中标供应商名称：', "采购人单位联系人：", '招标代理机构：', '报价明细附件：', '采购项目编号：', '采购计划编号：', '项目受理编号：', '招标文件编号：', '招标文件编号:', '招标项目编号：', '项目统一代码：', '项目统一代码:', '中标金额（元）', '中标金额(元)', '中标总价（元）', '中标总价(元)', '中标价（元）：', '中标价（元）:', '中标价（万元）', '中标价(万元)', '成交金额（元）', '成交金额(元)', '成交价（元）：', '成交价（元）:', '中标、成交金额', '最终报价（元）', '（预算金额）:', '最高限价金额：', '最高投标限价：', '（最高限价）：', '（预算金额）：', '预算金（元）:', '本项目预算金额', '本项目总预算约', '预算上限值为：', '最高投标限价为', '采购单位名称：', '采购单位名称:', '中标供应商名称', '第一中标候选人', '成交候选人：', '联系人电话：', '中标候选人：', '招标人编号：', '招标人编号:', '采购人编号：', "项目编号：", "采购人地址：", '采购文件编号', '招标项目名称', '中标工程名称', "唱价时间：", "投标报价：", '总中标金额：', '总中标金额:', '中标价（元）', '中标价(元)', "联系地址：", '总成交金额：', '总成交金额:', '最终报价为：', '最终报价为:', '招标控制价:', '预计标的额：', '项目总投资：', '采购总预算：', '项目上限价：', '预算金额为：', '最高限价为：', '项目预算为：', '采购预算为：', '预算总金额为', '投资总金额为', '项目预算金额', '项目预算金额', '委托方名称：', '招标人名称:', '招标人名称：', '采购单位名称', '建设单位名称', "成交下浮率：", '招 标 人：', '招 标 人:', '采购人名称：', '采购人名称:', '中标供应商：', '成交人名称:', '成交人名称：', '成交单位名称', '公示时间：', '联系电话：', '法人代表:', '开标时间：', '中标人信息', '联系方式：', '评审时间：', '法人代表：', '评审日期：', '标段编号：', '项目编号:', '招标编号：', '招标编号:', '采购编号：', '采购编号:', '机构编号：', '代理编号：', '委托编号：', '竞价编号：', '文件编号：', '工程编号：', '工程编号:', '项目名称：', '项目名称:', '工程名称：', '工程名称:', '标的名称：', '标的名称:', '中标金额：', '中标金额:', '中标总价：', '中标总价:', '中标价格：', '中标价格:', '成交金额：', '成交金额:', '成交总价：', '成交总价:', '成交价格：', '成交价格:', '总价(元)', '总价(元)', '最高限价：', '采购预算：', '采购预算:', '最高限价：', '预算金额：', '预算金额:', '预算限额：', '项目预算：', "中标费率：", '最高限额：', '控制金额：', '采购金额：', '项目预算:', '框架预算:', '预估金额：', '项目金额：', '采购估算：', '招标预算:', '预算金额为', '总价上限为', '预算总额：', '最高限价为', '控制金额为', '招标机构：', '招标单位：', '招标单位:', '投标人名称', '采购机构:', '采购机构：', '建设单位:', '建设单位：', '中标人名称', '中标人全称', '成交单位:', '成交单位：', '采购方式：', '招标方式：', "法定代表人：",  '采购方式:', '竞争性磋商', '竞争性谈判', '招标方式：', '制造商：', '联系人：', "交货期：", '采购编号', '工程编号', '公告编号', '项目名称', '工程名称', '中标价：', '中标价:', '成交价：', '成交价:', '中标金额', '成交金额', '中标价 ', '成交价 ', '采购预算', '预算价：', '控制价：', '控制价为', '投资预算', '总预算为', '最高预算', '最高限价', '预算金额', '控制金额', '招标机构', '招标人：', '招标人:', '采购人：', '采购人:', '委托人:', '委托人：', '中标单位', '中标人：', '中标人:', '单一来源', '（1）', '（2）', '（3）', '（4）', '（5）', '（6）', '预算约', '招标人', '地址：', '一、', '二、', '三、', '四、', '五、', '六、', '七、', '八、', '九、', '十、', '1、', '2、', '3、', '4、', '5、', '6、', '7、', '8、', '9、', '1．', '2．', '3．', '4．', '5．', '6．', '7．', '8．', '9．','（一）','（二）','（三）', '（四）', '（五）', '（六）', '（七）', '（八）', '（九）']               
        for key, rule_list in input_dict.items():
            for word in rule_list:
                if '#' not in word and word not in rep_list:
                    if ":" in word or "：" in word:
                        rep_list.append(word)
                        if word not in self.unknow_dict[key]:
                            self.unknow_dict[key].append(word)
        rep_list = sorted(rep_list, key = lambda i:len(i),reverse=True)
        input_doc = input_doc.replace(" </span>", "</span>")
        input_doc = input_doc.replace(" <span", "<span")
        if "中国电信-阳光采购网外部门户" in input_doc:
            content = str(self.reg1.sub('', input_doc))
        else:
            res = etree.HTML(input_doc)
            content = str(res.xpath('string(.)'))
    #        content = input_doc
    #        print (content)
            content = str(self.reg1.sub('', content))
        rep_doc = ""
        """
        预招标才需要
        """
        if notice_status == "预招标公告" and "广东省政府采购网" in input_doc:
            n_res = re.findall('<table.*?/table>', input_doc, re.S)
            for i in range(len(n_res)):
                new_res = etree.HTML(n_res[i])
                data1 = new_res.xpath('//table/tbody/tr/td/text()')
                data1 = [x for x in data1 if x!=" " and x!='\n' and "附件" not in x]
                remove_list = []
                for x in data1:
                    x_res = re.findall(x + '.*?</td', n_res[i], re.S)[0]
                    if "<input" not in x_res:
                        remove_list.append(x)
                for r in remove_list:
                    data1.remove(r)
                data1 = [x.replace(' ', '') for x in data1]
                data1 = [x.replace('\n', '') for x in data1]
                data1 = [x.replace('\t', '') for x in data1]
                while '' in data1:
                    data1.remove('')
                data1 = [x for x in data1 if x!=" " and x!='\n' and "附件" not in x]
                data2 = new_res.xpath('//table/tbody/tr/td/input/@value')
                if "发布时间：" in data1 and data1[-1] == "日" and data1[-2] == "月" and data1[-3]=="年":
                    new_data1 = data2[-3] + data1[-3] + data2[-2] + data1[-2] + data2[-1] + data1[-1]
                    for x in data1[-3:]:
                        data1.remove(x)
                    for x in data2[-3:]:
                        data2.remove(x)
                    data2.append(new_data1)
                for x in data1:
                    content = content.replace(x, '')
                for i in range(len(data1)):
                    if i >= len(data2):
                        data2[i] = ' '
                    content = content + data1[i] + data2[i] +'\n'

        content = content.replace(' 万元', '万元')
        content = content.replace('\n', ' ')
        content = content.replace('\xa0',' ')
        content = content.replace('\\r', ' ')
        content = content.replace('\\n', ' ')
        content = content.replace('\\t', ' ')
        content = content.replace('\r',' ')
        content = content.replace('\t', ' ')
        content = content.replace('&gt;', '')
        content = content.replace('&lt;/p', '')
        content = content.replace('&lt;p', '')
        content = content.replace('&lt;span', '')
        content = content.replace('&lt;/span', '')
        content = content.replace('&nbsp;', '')
        content = content.replace('  万元', '万元')
        content = content.replace(' 万元', '万元')
        content = content.replace('人民币 ', '人民币')
        content = content.replace('名 称', '名称')
        content = content.replace(' 年', '年')
        content = content.replace('年 ', '年')
        content = content.replace(' 月', '月')
        content = content.replace('月 ', '月')
        content = content.replace('  日', '日')
        content = content.replace('日  ', '日')
        content = content.replace(' 日', '日')
        content = content.replace('日 ', '日')
        content = content.replace('时 ', '时')
        content = content.replace(' 时', '时')
        content = content.replace('- ', '-')
        content = content.replace('。', ' 。 ')
        
        if "采招网" in content or "中 国采招" in content or "中国采 招" in content or "中国采招" in content or "中国 采招" in content:
            content = content.replace('      联系方式', '')
            content = content.replace(' 联系方式 ', '')
            content = content.replace(' 联系方式', '')
            content = content.replace('      查看企业资料', '')
            content = content.replace(' 查看企业资料 ', '')
            content = content.replace(' 查看企业资料', '')
            content = content.replace('#中国 采招网', ' #中国 采招网')
            content = content.replace('中国采招 网', ' 中国采招 网 ')
            content = content.replace('中 国采招', ' 中 国采招')
            content = content.replace('中国采 招', ' 中国采 招')
            content = content.replace('中国采招网', ' 中国采招网 ')
            content = content.replace('中国采 招网', '  中国采 招网 ')
            content = content.replace('（ bidcenter.com.cn）', '')
            content = content.replace('招标人         ', "招标人：")
            content = content.replace('建设单位        ', '建设单位：')
            content = content.replace('发包人名称             ', "发包人名称：")
            content = content.replace('发包人                ', "发包人：")
            content = content.replace('供应商        ', "供应商：")
            content = content.replace('成 交 价   ', '成 交 价：')
            content = content.replace('中 标 价   ', '中 标 价：')
            content = content.replace(' 成 交 结 果 公 告 ', "成交结果公告")
            content = content.replace('中标（成交）供应商（乙方）:           ', '中标（成交）供应商（乙方）:')
        for word in rep_list:
            if word in content and word not in rep_doc:
                x = '  ' + word
                content = content.replace(word, x)
                rep_doc += word + " "
        return content


    # 中文日期转数字
    """
    按年月日切分，再分别把对应的数字进行转换
    """
    def chinese2date(self, date_str):
        star = time.time()
        try:
            CN_NUM = {
                    '〇' : 0, '○': 0, '一' : 1, '二' : 2, '三' : 3, '四' : 4, '五' : 5, '六' : 6, '七' : 7, '八' : 8, '九' : 9, '零' : 0,
                    '壹' : 1, '贰' : 2, '叁' : 3, '肆' : 4, '伍' : 5, '陆' : 6, '柒' : 7, '捌' : 8, '玖' : 9, '貮' : 2, '两' : 2,
                }
            CN_UNIT = {"十": 10, "拾": 10, "〇": 0, "零": 0, '○': 0}
            date_str = date_str.replace('年', '-')
            date_str = date_str.replace('月', '-')
            date_str = date_str.replace('日', '')
            date_list = date_str.split('-')
            year_date = date_list[0]
            month_date = date_list[1]
            day_date = date_list[2]
            num_year = year_date
            for x in year_date:
                num_year = num_year.replace(x, str(CN_NUM[x]))
            if len(month_date) == 1:
                if month_date in CN_NUM:
                    num_month = str(CN_NUM[month_date])
                else:
                    num_month = str(CN_UNIT[month_date])
            else:
                num_month = str(CN_UNIT[month_date[0]] + CN_NUM[month_date[1]])
            if len(day_date) == 1:
                if day_date in CN_NUM:
                    num_day = str(CN_NUM[day_date])
                else:
                    num_day = str(CN_UNIT[day_date])
            elif len(day_date) == 2:
                if day_date[-1] in CN_UNIT:
                    num_day = str(CN_NUM[day_date[0]]*CN_UNIT[day_date[1]])
                else:
                    num_day = str(CN_UNIT[day_date[0]] + CN_NUM[day_date[1]])
            else:
                num_day = str(CN_NUM[day_date[0]]*CN_UNIT[day_date[1]] + CN_NUM[day_date[2]])
            num_date = num_year + '-' + num_month + '-' + num_day
        except:
            num_date = ""
        print ("日期中文转换：", time.time()-star)
        return num_date

    # 文本ac结果
    def get_ac_result(self, AC, doc):
        result_dict = {}
        for item in AC.iter(doc):
            if item[1][1] in result_dict:
                result_dict[item[1][1]].append(item[0])
            else:
                result_dict[item[1][1]] = [item[0]]
        return result_dict


    
    #获取开标时间
    def get_start_time(self, res):
#        print ('开标时间:', res)
        rep_list = ["\r", "\n", "\t", "\\r", "\\n", "\\t", "。", "上午"]
        ch_res = res
        if len(ch_res) != 0:
            chinese_str = "〇,○,一,二,三,四,五,六,七,八,九,零,拾,壹,贰,叁,肆,伍,陆,柒,捌,玖,貮,两,十"
            for i in range(len(ch_res)):
                ch_res[i] = ch_res[i].replace('/', '-')
                ch_res[i] = ch_res[i].replace('时', ':')
                ch_res[i] = ch_res[i].replace('分', '')
                ch_res[i] = ch_res[i].replace('：', ':')
                ch_res[i] = ch_res[i].replace('\u3000', '')
                fr_res = re.findall("(([0-9]{4}|[" + chinese_str + "]{4})+年+([0-9]{1,2}|[" + chinese_str + "]{1,2})+月+([0-9]{1,2}|[" + chinese_str + "]{1,3})+日+([0-9]{1,2})+\:+([0-9]{1,2}))", ch_res[i])
                if len(fr_res) > 0:
                    fr_res = [x[0] for x in fr_res]
                    ch_res[i] = fr_res[0]

            remove_list = [x for x in ch_res if "年" not in x or "月" not in x or "日" not in x]
            ch_res = [x for x in ch_res if x not in remove_list]
            
            for i in range(len(ch_res)):
                ch_res[i] = ch_res[i].replace('/', '-')
                res_word = ch_res[i]
                chinese_list = ['〇', '○', '一', '二', '三', '四', '五', '六', '七', '八', '九', '零', "拾",
                                '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖', '貮', '两', "十"]
                for n in chinese_list:
                    if n in res_word:
                        res_word = self.chinese2date(res_word)
                        break
                ch_res[i] = res_word
            
        if len(ch_res) == 0:
            nm_res = res
            for i in range(len(nm_res)):
                nm_res[i] = nm_res[i].replace('/', '-')
                nm_res[i] = nm_res[i].replace('时', ':')
                nm_res[i] = nm_res[i].replace('分', '')
                nm_res[i] = nm_res[i].replace('：', ':')
                fn_res = re.findall("(([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2}).*([0-9]{1,2})+:([0-9]{1,2}))", nm_res[i])
                if len(fn_res) > 0:
                    nm_res[i] = fn_res[0][0]
            remove_list = [x for x in nm_res if x.count('-')!=2]
            nm_res = [x for x in nm_res if x not in remove_list]
            res = nm_res
            res = [x for x in res if x != ""]
        else:
            res = ch_res
            res = [x for x in res if x != ""]
        for i in range(len(res)):
            if "年" in res[i] or "月" in res[i]:
                res[i] = res[i].replace('年', '-')
                res[i] = res[i].replace('月', '-')
                res[i] = res[i].replace('日', '~')
            res[i] = res[i].replace(' ', '~')
            res_word_list = res[i].split('-')
            if len(res_word_list) >= 3:
                if len(res_word_list[1]) == 1:
                    res_word_list[1] = "0" + res_word_list[1]
                if '~' in res_word_list[2]:
                    if len(res_word_list[2].split('~')[0]) == 1:
                        res_word_list[2] = "0" + res_word_list[2]
                res_word = "-".join(res_word_list)
                for rp_x in rep_list:
                    res_word = res_word.replace(rp_x, '')
                res[i] = res_word
        return res

    # 两个关键词的规则函数
    def two_word_match(self,result_dict, word_list, keyword_distance, tag, rule, final_result, distance_num,input_doc,result_rule_dict):
        rep_list = ["\r", "\n", "\t", "\\r", "\\n", "\\t"]
        word1_posi = result_dict[word_list[0]]
        word2_posi = result_dict[word_list[1]]
        for p1 in word1_posi:
            for p2 in word2_posi:
                if p2>p1 and p2-p1<=keyword_distance[rule]:
                    distance_num = p2-p1 if p2-p1<distance_num else distance_num
        if distance_num != 100000000:
            if tag == "购买标书截止日期":
                res = re.findall(word_list[0] + '(.*?)' + word_list[1] + '', input_doc)
#                res = [x for x in res if "至" in x]
                res = self.get_purchase_deadline(res)
            elif tag == "开标日期":
                res = re.findall(word_list[0] + '(.*?)' + word_list[1] + '', input_doc)
                res = self.get_start_time(res)
            else:
                res = re.findall(word_list[0] + '(.*?)' + word_list[1] + '', input_doc)
            num_list = [len(x) for x in res]
            if len(num_list) !=0:
                num = 0
#                num = num_list.index(min(num_list))
                res_word = res[num].strip(' ').replace('：', '')
                if '金额' in tag or '预算' in tag:
                    res_word = self.Money_data(res_word, ' '.join(word_list))
                if tag in final_result and res_word != '':
                    for rp_x in rep_list:
                        res_word = res_word.replace(rp_x, '')
                    if tag == "中标供应商" or tag == "招标人":
                        if word_list[1] == "公司":
                            res_word = res_word + "公司"
                    final_result[tag].append(res_word)
                    result_rule_dict[res_word] = ''.join(word_list)
                elif tag not in final_result and res_word != '':
                    for rp_x in rep_list:
                        res_word = res_word.replace(rp_x, '')
                    final_result[tag] = [res_word]
                    result_rule_dict[res_word] = ''.join(word_list)

        else:
            if tag not in final_result:
                final_result[tag] = []
        return final_result, result_rule_dict

    # 三个关键词的规则函数
    def three_word_match(self,result_dict, word_list, keyword_distance, tag, rule, final_result, distance_num,input_doc, result_rule_dict):
        rep_list = ["\r", "\n", "\t", "\\r", "\\n", "\\t"]
        word1_posi = result_dict[word_list[0]]
        word2_posi = result_dict[word_list[1]]
        word3_posi = result_dict[word_list[2]]
        for p1 in word1_posi:
            for p2 in word2_posi:
                for p3 in word3_posi:
                    if p2>p1 and p3>p2 and p3-p1<= keyword_distance[rule]:
                        distance_num = p3-p1 if p3-p1<distance_num else distance_num
        if distance_num != 100000000:
            res = re.findall(word_list[1] + '(.*?' + word_list[1] + '.*?)' + word_list[2], input_doc)
            num_list= [len(x) for x in res]
            if len(num_list) > 0:
                num = num_list.index(min(num_list))
                res_word = res[num].strip(' ').replace('：', '')
                if '金额' in tag or '预算' in tag:
                    res_word = self.Money_data(res_word, ' '.join(word_list))
                if tag not in final_result and res_word != '':
                    for rp_x in rep_list:
                        res_word = res_word.replace(rp_x, '')
                    final_result[tag] = [res_word]
                    result_rule_dict[res_word] = ''.join(word_list)
                elif tag in final_result and res_word != '':
                    for rp_x in rep_list:
                        res_word = res_word.replace(rp_x, '')
                    final_result[tag].append(res_word)
                    result_rule_dict[res_word] = ''.join(word_list)

        else:
            if tag not in final_result:
                final_result[tag] = []
        return final_result, result_rule_dict

    
    # 结果筛选
    """
    根据需要的数据格式用正则进行匹配及格式转换
    用关键词剔除一些无关结果
    有多个结果的按照匹配规则的长度选取（选取规则更长的）
    """
    def Choose_result(self, result_dict, result_rule_dict, html_doc, input_doc):
#        print (result_dict)
        for tag, result in result_dict.items():
            if len(result) > 0:
                remove_list = []
                            
                if tag == '项目编号':
                    for i in range(len(result)):
                        
                        if '（' in result[i] and '）' in result[i] and result[i].find('）')-result[i].find('（') > 5:
                            try:
                                n_result = re.findall('\（(.+)\）', result[i])[0]
                                result_rule_dict[n_result] = result_rule_dict[result[i]]
                                if len(n_result) > 3:
                                    result_dict[tag][i] = n_result
                                    result[i] = n_result
                            except:
                                result[i] = result[i]
                        elif '）' in result[i] and '（' in result[i] and result[i].find('）') <result[i].find('（'):
                            try:
                                n_result = re.findall('([0-9]*[A-Z]*.*?)\）', result[i])[0]
                                result_rule_dict[n_result] = result_rule_dict[result[i]]
                                if len(n_result) > 3:
                                    result_dict[tag][i] = n_result
                                    result[i] = n_result
                            except:
                                result[i] = result[i]
                        elif '）' in result[i] and '（' not in result[i]:
                            try:
                                n_result = re.findall('([0-9]*[A-Z]*.+)\）', result[i])[0]
                                result_rule_dict[n_result] = result_rule_dict[result[i]]
                                if len(n_result) > 3:
                                    result_dict[tag][i] = n_result
                                    result[i] = n_result
                            except:
                                result[i] = result[i]
                        elif ')' in result[i] and '(' not in result[i]:
                            try:
                                n_result = re.findall('([0-9]*[A-Z]*.+)\)', result[i])[0]
                                result_rule_dict[n_result] = result_rule_dict[result[i]]
                                if len(n_result) > 3:
                                    result_dict[tag][i] = n_result
                                    result[i] = n_result
                            except:
                                result[i] = result[i]
                        elif ']' in result[i] and '[' not in result[i]:
                            try:
                                n_result = re.findall('([0-9]*[A-Z]*.+)\]', result[i])[0]
                                result_rule_dict[n_result] = result_rule_dict[result[i]]
                                if len(n_result) > 3:
                                    result_dict[tag][i] = n_result
                                    result[i] = n_result
                            except:
                                result[i] = result[i]
                        elif '】' in result[i] and '【' not in result[i]:
                            try:
                                n_result = re.findall('([0-9]*[A-Z]*.+)\】', result[i])[0]
                                result_rule_dict[n_result] = result_rule_dict[result[i]]
                                if len(n_result) > 3:
                                    result_dict[tag][i] = n_result
                                    result[i] = n_result
                            except:
                                result[i] = result[i]
                    for res in result:
                        if len(res) > 60 or len(res) < 4:
                            remove_list.append(res)
                        re_res = re.findall('[0-9]|[A-Z]', res)
                        if len(re_res) == 0 or "投标" in res or "采购单位" in res or "单价" in res or "公示如下" in res or "结果如下" in res or "级别：" in res or "项目名称" in res or "得分排名" in res or "公告如下" in res or "建造师" in res or "招标人" in res or "后选人" in res or "评标" in res or "评审" in res or "评委" in res or "不涉及" in res or "任务详情" in res or "为准" in res or "公告期限" in res or "招标公示" in res or "招标公告" in res or "招标结果" in res or "成交" in res:
                            remove_list.append(res)
                
                if len(result_dict[tag]) > 1 and tag != "投标人":
                    money = 0
                    if '预算' in tag or '金额' in tag:
                        if tag == "中标金额":
                            zb_money = []
                            for x in result_dict[tag]:
                                if "中标" in result_rule_dict[x] and len(x.replace('元', '')) > 1:
                                    zb_money.append(x)
                                elif "table" in result_rule_dict[x] and len(x.replace('元', '')) >1:
                                    zb_money.append(x)
                            if len(zb_money) > 0:
                                result_dict[tag] = zb_money
                        res_leng = [len(result_rule_dict[r]) for r in result_dict[tag]]
                        num = res_leng.index(max(res_leng))
                        for x in result_dict[tag]:
                            x = result_dict[tag][num]
                            x = x.replace(',', '')
                            if '元' in x:
                                if '万元' in x:
                                    if '.' in x:
                                        x_re = re.findall('[0-9][0-9]*\.[0-9]*', x)[0]
                                        x = str(round(float(x_re)*10000, 2)) + '元' if x.find('万元') > x.find(x_re) and x.find('元') > x.find('万元') else x_re
                                    else:
                                        x_re = re.findall('[0-9][0-9]*', x)[0]
                                        x = str(round(float(x_re)*10000, 2)) + '元' if x.find('万元') > x.find(x_re) and x.find('元') > x.find('万元') else x_re
                                else:
                                    x = re.findall('[0-9][0-9]*\.+[0-9]*', x)[0] + '元' if '.' in x else re.findall('[0-9][0-9]*', x)[0] + '元'
                                result_dict[tag] = [x]
                                money = 1
                                break
                            else:
                                x = re.findall('[0-9][0-9]*\.+[0-9]*', x)[0] + '元' if '.' in x else re.findall('[0-9][0-9]*', x)[0] + '元'
                                result_dict[tag] = [x]
                                money = 1
                                break
                        if money == 0:
                            num_list= [len(result_rule_dict[x]) for x in result_dict[tag]]
                            num = num_list.index(max(num_list))
                            result_dict[tag] = [result_dict[tag][num]]
                    else:
                        new_res = []
                        new_rule = []
                        for x in result_dict[tag]:
                            if ':' in result_rule_dict[x] or '：' in result_rule_dict[x]:
                                if "候选" not in result_rule_dict[x]:
                                    new_res.append(x)
                                    new_rule.append(result_rule_dict[x])
                        if len(new_res) > 0 and len(new_rule) > 0:
                            num_list = [len(y) for y in new_rule]
                            num = num_list.index(max(num_list))
                            result_dict[tag] = [new_res[num]]
                        else:
                            new_res = []
                            new_rule = []
                            for x in result_dict[tag]:
                                if 'table' in result_rule_dict[x]:
                                    new_res.append(x)
                                    new_rule.append(result_rule_dict[x])
                        if len(new_res) > 0 and len(new_rule) > 0:
                            num_list = [len(y) for y in new_rule]
                            num = num_list.index(max(num_list))
                            result_dict[tag] = [new_res[num]]
                        else:
                            num_list= [len(result_rule_dict[x]) for x in result_dict[tag]]
                            num = num_list.index(max(num_list))
                            result_dict[tag] = [result_dict[tag][num]]
#                        num_list= [len(result_rule_dict[x]) for x in result_dict[tag]]
#                        num = num_list.index(max(num_list))
#                        result_dict[tag] = [result_dict[tag][num]]
                                
            if len(result_dict[tag]) == 0:
                if tag != "废标":
                    unknow_list = self.unknow_dict[tag]
                    un_num = 0
                    for unknow_word in unknow_list:
                        if unknow_word in input_doc:
                            un_num += 1
                    if un_num == 0:
                        result_dict[tag] = ["-2"]
                    else:
                        result_dict[tag] = ['-1']
            elif len(result_dict[tag]) > 0:
                if result_dict[tag][0] == "":
                    result_dict[tag] = ["-2"]
        return result_dict

    # 主函数
    def get_main_item(self, json_str):
        start_time = time.time()
        print ('开始时间', datetime.datetime.now())
        # 建立ac自动机.decode()
        """
        参数没有传入则为空list，两个关键词的list按元素长度排列
        """
        rep_list = ["\r", "\n", "\t", "\\r", "\\n", "\\t"]
        json_input = json.loads(json_str)
        if "input_dict" in json_input:
            input_dict = json_input["input_dict"]
        else:
            input_dict = {}
            
        if "暂停公告" in input_dict:
            stop_list = input_dict["暂停公告"]
            del input_dict["暂停公告"]
        else:
            stop_list = []
            
        if "重招标公告" in input_dict:
            restart_list = input_dict["重招标公告"]
            del input_dict["重招标公告"]
        else:
            restart_list = []
            
        if "延期公告" in input_dict:
            delay_list = input_dict["延期公告"]
            del input_dict["延期公告"]
        else:
            delay_list = []
            
        if "修改公告" in input_dict:
            change_list = input_dict["修改公告"]
            del input_dict["修改公告"]
        else:
            change_list = []
            
        if "notice_id" in json_input:
            notice_id = json_input["notice_id"]
        else:
            notice_id = ""

        if "input_doc" in json_input:
            input_doc = self.del_html(json_input["input_doc"], input_dict)
        else:
            input_doc = " "
        
        print ("数据加载", datetime.datetime.now())
        
        # 采招网大部分是不含：，因此需要增加去掉冒号的规则
        if "采招网" in input_doc or "采 招网" in input_doc or "采招 网" in input_doc  or "中国 采招" in input_doc:
            for key in input_dict:
                for i in range(len(input_dict[key])):
                    if input_dict[key][i] != "采购方：" and input_dict[key][i] != "采购方:":
                        input_dict[key].append(input_dict[key][i].replace(":", ""))
                        input_dict[key].append(input_dict[key][i].replace("：", ""))
            word_remove = []
            for x in input_dict["项目名称"]:
                if x[-2:] == "工程" or x == "工程项目":
                    word_remove.append(x)
            input_dict["项目名称"] = [x for x in input_dict["项目名称"] if x not in word_remove]
            input_dict["招标人"] = [x for x in input_dict["招标人"] if x not in ["甲方"]]
            input_dict["中标供应商"] = [x for x in input_dict["中标供应商"] if x not in ["乙方"]]
        if "华润集团守正电子招标平台" in input_doc:
            pro_rule = input_dict["项目名称"]
            pro_rule = [x for x in pro_rule if "项目名称" not in x and "标段名称" not in x and "标的名称" not in x and "标包名称" not in x]
            input_dict["项目名称"] = pro_rule
        Match_Ac = ahocorasick.Automaton()
        # 获取各个规则的距离
        keyword_distance = {}
        for rule_list in input_dict.values():
            for rule in rule_list:
                keyword_list = str(rule).split('|')
                dis_list = [[x.split('_')[0], x.split('_')[1]] for x in keyword_list if '_' in x]
                dis_list += [[x, 50] for x in keyword_list if '_' not in x]
                for d_rule in dis_list:
                    keyword_distance[d_rule[0]] = float(d_rule[1])
        # 把规则关键词传入ac
        for rule_word in keyword_distance.keys():
            for index,word in enumerate(str(rule_word).split('#')):
                Match_Ac.add_word(word, (index, word))
        # ac建立完成
        Match_Ac.make_automaton()
        # 获取ac结果
        result_dict = self.get_ac_result(Match_Ac, input_doc)
        print ("ac结果获取", datetime.datetime.now())
        # 进行规则匹配
        final_result = {}
        result_rule_dict = {}
        for tag, rule_list in input_dict.items():
            for rule in rule_list:
                rule = rule.split('_')[0]
                word_list =  rule.split('#')
                tag_status = True

                for word in word_list:
                    if word not in result_dict:
                        tag_status = False
                
                if tag_status:
                    distance_num = 100000000
                    for i in range(len(word_list)):
                        word_list[i] = word_list[i].replace('(', '\(')
                        word_list[i] = word_list[i].replace(')', '\)')
                    if len(word_list) == 2:
                        final_result,result_rule_dict = self.two_word_match(result_dict, word_list, keyword_distance, tag, rule, final_result, distance_num,input_doc, result_rule_dict)
                    elif len(word_list) == 3:
                        final_result,result_rule_dict = self.three_word_match(result_dict, word_list, keyword_distance, tag, rule, final_result, distance_num,input_doc, result_rule_dict)
                    elif len(word_list) == 1:
                        if tag == "开标日期" or tag == "开标变更时间":
                            res = re.findall(word_list[0] + '+([^\s].*?)  ', input_doc)
                            if len(res) == 0:
                                res = re.findall(word_list[0] + ' +([^\s].*?)  ', input_doc)
                            res = self.get_start_time(res)
                        else:
                            res = re.findall(word_list[0] + '+([^\s].*?) ', input_doc)
                            if len(res) == 0:
                                res = re.findall(word_list[0] + ' +([^\s].*?) ', input_doc)
                            if len(res) >0:
                                if tag == "项目编号":
                                    res = [x for x in res if x != "分散"]
                                    for i in range(len(res)):
                                        if "，" in res[i]:
                                            try:
                                                res[i] = re.findall('.*?\，', res[i])[0]
                                            except:
                                                res[i] = res[i]
                                        elif "；" in res[i]:
                                            try:
                                                res[i] = re.findall('.*?\；', res[i])[0]
                                            except:
                                                res[i] = res[i]
                        if len(res) > 0 and tag != "投标人":
                            num_list = [len(x) for x in res]
                            res_word = res[num_list.index(min(num_list))].strip('：')
                            if tag not in final_result and res_word != '':
                                for rp_x in rep_list:
                                    res_word = res_word.replace(rp_x, '')
                                final_result[tag] = [res_word]
                                if rule == "编号" or rule == "编号：" or rule == "编号:":
                                    if res_word in result_rule_dict:
                                        if len(rule) > len(result_rule_dict[res_word]):
                                            result_rule_dict[res_word] = rule
                                    else:
                                        result_rule_dict[res_word] = rule
                                elif '：' in rule or ':' in rule:
                                    if res_word in result_rule_dict:
                                        if len(result_rule_dict[res_word]) < len(rule+'sadaa'): 
                                            if "中标" in rule or "项目名称" in rule or "成交" in rule:
                                                result_rule_dict[res_word] = rule+'sadaasad'
                                            else:
                                                result_rule_dict[res_word] = rule+'sadaa'
                                    else:
                                        if "中标" in rule or "项目名称" in rule or "成交" in rule:
                                            result_rule_dict[res_word] = rule+'sadaasad'
                                        else:
                                            result_rule_dict[res_word] = rule+'sadaa'
                                else:
                                    if res_word in result_rule_dict:
                                        if len(rule) > len(result_rule_dict[res_word]):
                                            result_rule_dict[res_word] = rule
                                    else:
                                        result_rule_dict[res_word] = rule
                            elif tag in final_result and res_word != '':
                                for rp_x in rep_list:
                                    res_word = res_word.replace(rp_x, '')
                                final_result[tag].append(res_word)
                                if rule == "编号" or rule == "编号：" or "rule" == "编号:":
                                    if res_word in result_rule_dict:
                                        if len(rule) > len(result_rule_dict[res_word]):
                                            result_rule_dict[res_word] = rule
                                    else:
                                        result_rule_dict[res_word] = rule
                                elif '：' in rule or ':' in rule:
                                    if res_word in result_rule_dict:
                                        if len(result_rule_dict[res_word]) < len(rule+'sadaa'): 
                                            if "中标" in rule or "项目名称" in rule or "成交" in rule:
                                                result_rule_dict[res_word] = rule+'sadaasad'
                                            else:
                                                result_rule_dict[res_word] = rule+'sadaa'
                                    else:
                                        if "中标" in rule or "项目名称" in rule or "成交" in rule:
                                            result_rule_dict[res_word] = rule+'sadaasad'
                                        else:
                                            result_rule_dict[res_word] = rule+'sadaa'
                                else:
                                    if res_word in result_rule_dict:
                                        if len(rule) > len(result_rule_dict[res_word]):
                                            result_rule_dict[res_word] = rule
                                    else:
                                        result_rule_dict[res_word] = rule
                        else:
                            if tag not in final_result:
                                final_result[tag] = []
                else:
                    if tag not in final_result:
                        final_result[tag] = []
        
        print ('初步结果', final_result)
#####        print (result_rule_dict)
        print ("初步解析完成：", datetime.datetime.now())
        # 供应商，招标人中有：，获取：后的结果
        
        # 获取匹配结果报错信息
        content = ''
        for tag in final_result:
            final_result[tag] = list(set(final_result[tag]))
            if len(final_result[tag]) > 1:
                content += tag + ' --- 匹配结果过多；   '
               
        print ("结果对应规则：", result_rule_dict)
        
        print ("匹配筛选:", datetime.datetime.now())
        # 匹配结果筛选
        final_result = self.Choose_result(final_result, result_rule_dict, json_input["input_doc"], input_doc) 

        for tag in final_result:
            if len(final_result[tag])>0:
                final_result[tag] = [x.replace(' ', '') for x in final_result[tag]]
                
        # 判断是否为废标
#        if "废标" in final_result:
#            final_result["废标"] = ['True'] if len(final_result["废标"]) > 0 else ["False"]
            
       
        if "项目编号" in final_result:
            final_result["项目编号"][0] = final_result["项目编号"][0].replace('，', '')
            final_result["项目编号"][0] = final_result["项目编号"][0].replace('；', '')
            final_result["项目编号"][0] = final_result["项目编号"][0].replace('、', '')
            final_result["项目编号"][0] = final_result["项目编号"][0].replace(')：', '')
            final_result["项目编号"][0] = final_result["项目编号"][0].replace('。', '')
        if "开标变更时间" in final_result:
            final_result["开标变更时间"][0] = str(final_result["开标变更时间"][0]).replace('~', ' ')
        for key, values in final_result.items():
            if key not in ["招标人区域", "供应商区域"]:
                if len(values) > 0:
                    if values[0] == '':
                        final_result[key] = ['-1']
                else:
                    final_result[key] = ['-1']
        
        change_type = ""
        for word in stop_list:
            if word in input_doc:
                change_type = "暂停公告"
                break
        if change_type == "":
            for word in restart_list:
                if word in input_doc:
                    change_type = "重招标公告"
                    break
        if change_type == "":
            for word in change_list:
                if word in input_doc:
                    change_type = "修改公告"
        if change_type == "":
            for word in delay_list:
                if word in input_doc:
                    change_type = "延期公告"
        if change_type == "":
            change_type = "修改公告"
        final_result["公告类型"] = [change_type]
        nes_list = ["项目编号", "开标变更时间"]
        for n_key in nes_list:
            if n_key not in final_result:
                final_result[n_key] = ['-2']
        # 保存文本（线上用， 本地注释）
#        print ('文本保存')
#        es_access_doc = 'http://47.112.138.184:9202'
#        es_index_doc = 'htmltext'
#        doc_type_doc= 'doc'
#        save_data = {'notice_id': final_result['notice_id'], 'text':input_doc}
#        html_text.write_text(save_data, es_access_doc,es_index_doc,doc_type_doc)

        print ('结果：', final_result)
        print ('结束时间', datetime.datetime.now())
        end_time = time.time()
        print ("运行耗时：%s" % str(end_time-start_time))
        return final_result


if __name__=="__main__":
    ac = Ac_match()
#    url = "http://my.zbyjw.cn/detail/2019111912055412.html"
#    doc = requests.get(url)
#    doc.encoding = "utf-8"
#    input_doc = doc.text
    input_dict = {'项目编号': ['采购项目编号：', '标段（包）编号：', '标段编号：', '项目编号:', '项目编号', '招标编号：', '招标编号:', '招标编号', '采购编号：', '采购编号:', '采购编号', '机构编号：', '采购计划编号：', '代理编号：', '委托编号：', '招标人编号：', '招标人编号:', '采购人编号：', '项目受理编号：', '招标文件编号：', '招标文件编号:', '采购文件编号', '招标项目编号：', '竞价编号：', '文件编号：', '工程编号：', '工程编号:', '工程编号', '项目统一代码：', '项目统一代码:', '公告编号', '比选代理机构编号：', '编号：', '项目编号：', '采购代理编号：', '采购项目编码：', '项目[#]的招评标_30', '招标代理编号：', '编号:', '招标代理机构编号：', '公告编号:', '标的编号', '采购 编号：', '比选代理编号：', '项目包编号：', '询价编号：', '采购项目编号（采购计划编号）：', '项目名称及项目编号：', '公共资源交易编号：', '采购项目名称及编号：', '招标编号为', '采购项目名称及招标编号：', '采购项目名称及标书编号：', '采购项目名称及项目编号：', '标包编号：', '政府采购编号 ：', '合同编号：', '项目标号：', '询价书编号：', '采购公示编号：', '比选编号:', '采购代理机构编号：', '计划编号：', '比选编号：', '单一来源编号：', '合同编号', '招标编号为#的_30', '项目编号为#的_30', '项目编号为', '编号为：', '项目号：', '项目编码：', '包件编码:', '项目标号：', '合同号（订单号）：', '招标项目名称及标书编号：', '项 目 编 号：', '入场登记号：'],
                  "开标变更时间": ["截止时间和开标时间：", "开标时间:"],
                  "暂停公告": ["暂停公告", "暂停招标"],
                  "延期公告": ["变更至", "重大修改"],
                  "重招标公告":["恢复本项目采购", "恢复采购"],
                  "修改公告": ["开标时间不变"]
                  }
    
#    data = {"input_dict": input_dict, "input_doc": input_doc, "sup_keyword_list": sup_keyword_list, "sup_table_dict": sup_table_dict}
#    final,jx_doc = ac.get_main_item(json.dumps(data))
    
#    import pymysql
#    import pandas as pd
#    conn = pymysql.connect("47.112.138.184","dict","tisson1!","crawler", charset="utf8mb4", use_unicode=True, port=3308)
##    sql = 'select html from t_notice where id=419854'
#    """中标"""
#    sql = """SELECT html FROM t_notice WHERE ID= (SELECT REPLACE(BIDDING_PROPERTIES->'$.notices','"','') FROM t_bidding_manual WHERE ID = 235885)"""
#    
#    """招标"""
##    sql = """SELECT html FROM t_notice WHERE OBJECT_ID = (SELECT OBJECT_ID FROM t_bidding_call WHERE ID = 420755)"""
#    html_code = pd.read_sql(sql, con=conn)["html"][0]
#    input_doc = html_code
                   
    url = "http://ggzy.gz.gov.cn/jyywzfcgzfcggggzgg/672023.jhtml"
    doc = requests.get(url)
    doc.encoding = "utf-8"
    input_doc = doc.text
    data = {"input_dict": input_dict, "input_doc": input_doc}
    final,jx_doc = ac.get_main_item(json.dumps(data))
    
    """附件解析失败objectid"""
#    sql = "SELECT * FROM t_notice_file_url f WHERE IS_CRAWL = '1' AND RE_EXTRACT = -2"
    